extends Node
@onready var 联机的ui: Control = $UI/联机UI
@onready var players: Node = $players
@onready var host: Button = $UI/联机UI/VBoxContainer/host
@onready var 通知: Label = $UI/联机UI/通知
@onready var 服务器广播: FuWuQIGuangBo = $自动联机/服务器广播
@onready var 客户端监听: keHuDuanJianTing = $自动联机/客户端监听
@onready var 断开连接: Label = $UI/联机UI/VBoxContainer/断开连接
@onready var 手输ip: LineEdit = $UI/联机UI/VBoxContainer/客户端/加入/手输ip
@onready var join: Button = $UI/联机UI/VBoxContainer/客户端/加入/join
@onready var 设置: FoldableContainer = $UI/设置
@onready var 地图总节点: 地图管理器 = $地图总节点
@onready var 服务器大厅: Label = $UI/服务器大厅/等待客户端进入标语/标语


var  serverPOST:int =7760
const MAIN_PLAYER = preload("uid://id8t07pq47ty")
const wifi地址:="192.168.31.72"
var peer:=ENetMultiplayerPeer.new()

func 初始化网络联机():
	ProjectSettings.set_setting("input_devices/pointing/emulate_mouse_from_touch",true)
	players.remove_all_children()
	联机的ui.visible=true
	服务器大厅.visible=false
	设置.folded=true
	multiplayer.multiplayer_peer=null
	peer=ENetMultiplayerPeer.new()
	客户端监听.discovered_servers={}
	客户端监听.first_server_info= {"address":"", "port":-1, "name": ""}
	服务器广播.stop_broadcasting()
	客户端监听.start_scanning()
	地图总节点.初始地图()
func _ready() -> void:
	print_Local_IP4_Add()
	初始化网络联机()
	multiplayer.peer_connected.connect(_on_peer_connected)
	multiplayer.connected_to_server.connect(_on_connected_to_server)
	multiplayer.connection_failed.connect(_on_connection_failed)
	multiplayer.peer_disconnected.connect(_on_peer_disconnected)
	multiplayer.server_disconnected.connect(_on_server_disconnected)
func _on_connected_to_server():
	print("客户端成功连接服务器")
func _on_host_button_up() -> void:
	联机的ui.visible=false
	设置.folded=true
	ProjectSettings.set_setting("input_devices/pointing/emulate_mouse_from_touch",false)
	客户端监听.stop_scanning()
	while peer.create_server(serverPOST)!=OK :
		serverPOST+=1
	multiplayer.multiplayer_peer=peer
	服务器广播.start_broadcasting(serverPOST)
	print("服务器创建于端口"+str(serverPOST))
	add_player(peer.get_unique_id())
	服务器大厅.visible=true
	地图总节点.进入大厅()
func _on_join_button_up() -> void:
	ProjectSettings.set_setting("input_devices/pointing/emulate_mouse_from_touch",false)
	# 获取第一个服务器的地址
	
	var first_server_infow:Dictionary = 客户端监听.first_server_info
	var server_port_k=first_server_infow.port
	var loc_ip = first_server_infow.address
	if loc_ip == "":
		通知.text="未发现任何服务器，请等待扫描或检查网络"
		await get_tree().create_timer(1.0).timeout
		通知.text=""
		return
	if "192.168." not in loc_ip:
		通知.text="IP地址错误，请核对"
		await get_tree().create_timer(1.0).timeout
		通知.text=""
		return
	var error = peer.create_client(str(loc_ip), server_port_k)
	
	if error == OK:
		multiplayer.multiplayer_peer = peer
		联机的ui.visible=false
		客户端监听.stop_scanning()
	else:
		print(error)
		通知.text="连接失败！IP地址错误，请核对  _ERROR["+str(error)+"]"
		await get_tree().create_timer(2).timeout
		通知.text=""
		return
func _on_peer_connected(idd :int):
	服务器大厅.visible=false
	var self_id=str(multiplayer.get_unique_id())
	print("本机对等点属性ID是"+self_id)
	print("连接目标对等点ID为："+str(idd))
	print("————————————————————————————————————————————————————————————————————————")		
	print(" ")
	服务器广播.stop_broadcasting()
	客户端监听.stop_scanning()
	if multiplayer.is_server():
		var p1=get_node("players/1")
		p1.position=Vector2(100,100)
		p1.发射子弹许可=true
	if self_id=="1" :
		add_player(idd)
	
	地图总节点.更换地图()
	
func print_Local_IP4_Add()->void:#控制台输出内网地址
	var ip=IP.get_local_addresses()
	for i in ip:
		if ":" not in i:
			if "192.168" in i:
				pass
				#print(i)
func _on_connection_failed(id :int):#无法与服务器建立连接时发出。仅在客户端上发出。
	通知.text="IP地址下未找到服务器"
	await get_tree().create_timer(1.0).timeout
	通知.text=""
	联机的ui.visible=true
	print("connection_failed"+"本机对等点ID为："+str(id))
	pass
func _on_peer_disconnected(_id :int):#与对等体断开连接时发出。当某个客户端从同一服务器断开连接时，其他客户端会收到通知。
	初始化网络联机()#所有玩家清除，完全重置，返回UI界面
func _on_server_disconnected(id :int):#与服务器断开连接时发出。仅在客户端上发出。
	联机的ui.visible=true
	print("服务器_disconnected"+"本机对等点ID为："+str(id))
	
	
	pass
func add_player(id:int):
	var player=MAIN_PLAYER.instantiate() as Player
	player.name=str(id)
	print(str(id)+"负值idd")
	player.set_multiplayer_authority(1)#处理权限归属服务器
	players.add_child(player)
func _on_本地测试_button_up() -> void:
	ProjectSettings.set_setting("input_devices/pointing/emulate_mouse_from_touch",false)
	var loc_ip:="127.0.0.1"
	if false:
		通知.text="IP地址错误，请核对"
		await get_tree().create_timer(1.0).timeout
		通知.text=""
		return
	var error = peer.create_client(str(loc_ip), serverPOST)
	if error == OK:
		multiplayer.multiplayer_peer = peer
		通知.text="连接成功！"
		联机的ui.visible=false
	else:
		print(error)
		通知.text="连接失败！IP地址错误，请核对  _ERROR["+str(error)+"]"
		return
func _on_重启_button_up() -> void:
	初始化网络联机()
func _process(_delta: float) -> void:
	
	pass	
